import modelExtend from 'dva-model-extend'
import {lwjPageModel} from 'utils/model'
import pathToRegexp from 'path-to-regexp'
import {routerRedux} from 'dva/router'
import {query,queryClassifyList} from './service'
import { message } from 'antd'
import {turnToTreeData} from 'utils/index'
import lodash from 'lodash'

export default modelExtend(lwjPageModel, {
  namespace: 'orderSalesmarket',
  state: {
    classifyList: [],
    productList: [],
    queryParam: {},
    detailModal: false,
    detailUrl: '',
    pagination: {},
    salesDistributorId: null,
    item: null,
    pagination: {
        current: 1,
        total: 0,
        showTotal: total => `共 ${total} 条`,
        showSizeChanger: true,
        showQuickJumper: true,
        defaultPageSize: 10,
        pageSize: 10
    },
    cartList: [],
    cartVisible: false,
    totalChannelPrice: 0.00,
    totalPrice: 0.00,
    totalRetailPrice: 0.00,
    count: 0
  },
  subscriptions: {
    setup({dispatch, history}) {
      history.listen((location) => {
        const match = pathToRegexp('/order/salesmarket').exec(location.pathname);
        if(match && !location.state){
          dispatch({
            type: 'goDashboard'
          })
          return;
        }
        if(match){
          dispatch({
            type: 'reset',
            item: (location.state.item ? location.state.item : null),
            salesDistributorId: (location.state.salesDistributorId ? location.state.salesDistributorId : null)
          })
          if(location.state.cartList){
            dispatch({
              type: 'setCartList',
              cartList: location.state.cartList
            })
          }
          dispatch({
            type: 'query',
            payload: {
              start: 0,
              limit: 10
            }
          })
          dispatch({
            type: 'queryClassifyList'
          })
        }
      })
    }
  },
  effects: {
    * query({
        payload
    }, {call, put, select}) {
      let salesDistributorId = yield select(({orderSalesmarket}) => orderSalesmarket.salesDistributorId);
      let queryParam = yield select(({orderSalesmarket}) => orderSalesmarket.queryParam);
      const {result: data} = yield call(query, { 
        start: payload.start,
        limit: payload.limit,
        cateIdAndChild: queryParam.cateIdAndChild,
        name: queryParam.name,
        goods_id: queryParam.goods_id,
        id: queryParam.id,
        status: queryParam.status,
        sort: 'id',
        order: 'DESC',
        distributorId: (salesDistributorId ? salesDistributorId : null)
      });
      yield put({
          type: 'success',
          payload: {
            list: data.content,
            pagination: {
                current: payload.start + 1,
                total: data.totalElements,
                showTotal: total => `共 ${total} 条`,
                showSizeChanger: true,
                showQuickJumper: true,
                defaultPageSize: 10,
                pageSize: data.size
            }
          }
      });
    },
    * queryClassifyList({}, {call, put, select}) {
      const {result: data} = yield call(queryClassifyList);
      let _temp = turnToTreeData(data, 'name', 'id', 'pid');
      yield put({
          type: 'setClassifyList',
          classifyList: _temp
      });
    },
    * goDashboard({}, {call, put, select}){
      yield put(routerRedux.push('/dashboard'))
    },
    * goCartCaluate({cartList, totalChannelPrice, totalNumber}, {call, put, select}){
      let _temp = lodash.cloneDeep(cartList);
      let _ids = _temp.map(val => val.id).join("-");
      let _list = [];
      let item = yield select(({orderSalesmarket}) => orderSalesmarket.item);
      let salesDistributorId = yield select(({orderSalesmarket}) => orderSalesmarket.salesDistributorId);
      cartList.map(val => {
        _list.push({
          channelPrice: val.channel_price,
          distributorId: item.salesDistributorId,
          skuId: val.sku_id,
          name: val.commodity_name,
          quantity: val.number
        })
      })
      yield put(routerRedux.push(`/salesmarket/cartcaluate/1/${_ids}`, {list: lodash.cloneDeep(_list), cartList: cartList, item: lodash.cloneDeep(item), salesDistributorId: salesDistributorId}));
    },
  },

  reducers: {
    success(state, {payload}) {
      return {
        ...state,
        productList: payload.list,
        pagination: payload.pagination
      }
    },
    setCartList(state, {cartList}) {
      let totalChannelPrice = 0;
      let totalRetailPrice = 0;
      let totalPrice = 0;
      let count = 0;
      cartList.forEach((value, index) => {
        totalRetailPrice += (value.price * 10 * 10 * value.number);
        totalChannelPrice += (value.channel_price * 10 * 10 * value.number);
        count += value.number;
        totalPrice = totalChannelPrice;
      })
      return {
        ...state,
        cartList,
        totalRetailPrice: (totalRetailPrice/100).toFixed(2),
        totalChannelPrice: (totalChannelPrice/100).toFixed(2),
        totalPrice: (totalPrice/100).toFixed(2),
        count
      }
    },
    //请求类目列表数据
    setClassifyList(state, {classifyList}) {
      return {
        ...state,
        classifyList
      }
    },
    //列表搜索
    setQueryParam(state, {queryParam}) {
      return{
        ...state,
        queryParam
      }
    },
    //显示详情弹窗
    showProductDetail(state, {detailUrl}) {
      return {
        ...state,
        detailModal:true,
        detailUrl:detailUrl
      }
    },
    //关闭详情弹窗
    hideProductDetail(state, {}) {
      return {
        ...state,
        detailModal:false
      }
    },
    //显示选中条目弹窗
    showCartDrawer(state) {
      return {
        ...state,
        cartVisible: true
      }
    },
    //关闭选中条目弹窗
    hideCartDrawer(state) {
      return {
        ...state,
        cartVisible: false
      }
    },
    reset(state, {item,salesDistributorId}) {
      return{
        classifyList: [],
        productList: [],
        queryParam: {},
        detailModal: false,
        detailUrl: '',
        pagination: {},
        salesDistributorId: salesDistributorId,
        item: item,
        pagination: {
          current: 1,
          total: 0,
          showTotal: total => `共 ${total} 条`,
          showSizeChanger: true,
          showQuickJumper: true,
          defaultPageSize: 10,
          pageSize: 10
        },
        cartList: [],
        cartVisible: false,
        totalChannelPrice: 0.00,
        totalPrice: 0.00,
        totalRetailPrice: 0.00,
        count: 0,
        cartList: []
      }
    }
  }
})
